package com.example.java_gobang.api;

import com.example.java_gobang.Utils.PasswordUtils;
import com.example.java_gobang.model.User;
import com.example.java_gobang.model.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

@Slf4j
@RestController
public class UserAPI {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest request) {
        User user = userMapper.selectByName(username);
        log.info("login username = " + username);
        if (user != null) {
            try {
                boolean isValid = PasswordUtils.verifyPassword(password, user.getSalt(), user.getPassword());
                if (isValid) {
                    HttpSession httpSession = request.getSession(true);
                    httpSession.setAttribute("user", user);
                    return user;
                }
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                e.printStackTrace();
            }
        }
        log.info("登录失败!");
        return new User();

    }

    @RequestMapping("/register")
    public Object register(String username, String password) {
        try {
            String salt = PasswordUtils.generateSalt();
            String hashedPassword = PasswordUtils.hashPassword(password, salt);
            User user = new User();
            user.setUsername(username);
            user.setPassword(hashedPassword);
            user.setSalt(salt);
            userMapper.insert(user);
            log.info("用户：" + user.getUsername() + "注册成功！");
            return user;
        } catch (DuplicateKeyException | InvalidKeySpecException | NoSuchAlgorithmException e) {
            User user = new User();
            return user;
        }
    }

    @RequestMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest request) {
        try {
            HttpSession httpSession = request.getSession(false);
            User user = (User) httpSession.getAttribute("user");
            log.info("获取用户信息：{}", user);
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            return new User();
        }
    }
}
